import { IStorage, AbstractStorage } from './i-storage'


class AliMiniStorage {
  static save(key: string, value: any) {
    const ret = my.setStorageSync({key, data: value});
    return ret.success;
  }
    
  static load(key: string): any {
    const ret = my.getStorageSync({key});
    if (!ret.data) {
      return undefined;
    }
                
    return ret.data;
  }
    
  static remove(key: string) {
    my.removeStorageSync({key});
  }

  static keys(): Array<string> {
    const ret = my.getStorageInfoSync();
    return ret.keys;
  }

  static clear() {
    my.clearStorageSync();
  }
}


export class MiniStorage extends AbstractStorage {
  static clearAll() : boolean {
    AliMiniStorage.clear();
    return true;
  }

  constructor(namespace: string) {
    super(namespace);
  }

  implLoadString(key: string) : string | undefined {
    const ret = AliMiniStorage.load(key);
    if (!ret) {
      return undefined;
    }

    return (typeof ret === 'string')? ret : undefined;
  }

  implSaveString(key: string, value: string): boolean {
    let ret = true;
    const res = this.implLoadString(key);
    if (res) {
      ret = false;
    }
    return AliMiniStorage.save(key, value)? ret : false;
  }

  implLoadObject(key: string) : object | undefined {
    const ret = AliMiniStorage.load(key);
    if (!ret) {
      return undefined;
    }

    return (typeof ret === 'object')? ret : undefined;
  }
 
  implSaveObject(key: string, value: object): boolean {
    let ret = true;
    const res = this.implLoadObject(key);
    if (res) {
      ret = false;
    }
    return AliMiniStorage.save(key, value)? ret : false;
  }

  implDelete(key: string) : string | object | undefined {
    const ret = AliMiniStorage.load(key);
    if (ret) {
      AliMiniStorage.remove(key);
    }
    return ret;
  }

  implHas(key: string): boolean {
    return AliMiniStorage.load(key)? true : false;
  }

  getThisNsKeys(): Array<string> {
    const keys = AliMiniStorage.keys();
    return keys.filter((key) => key.startsWith(this.namespace));
  }

  //TODO: IStorage clear/size may be key conflict
  clear(): boolean {
    const fKeys = this.getThisNsKeys();
    for (const key of fKeys) {
        AliMiniStorage.remove(key);
    }
    return true;
  }

  size(): number {
    const fKeys = this.getThisNsKeys();
    return fKeys.length;
  }
}
